<template>
	<div>
		<BreadCrumb pathOne="内容管理" pathTwo="文章管理"></BreadCrumb>
		<div>
			<el-form :inline="true">
				<el-form-item label="文章名" size="large">
					<el-input clearable size="large" v-model="searchName" style="width: 240px" placeholder="请输入文章名" />
				</el-form-item>
				<el-form-item label="咨询师作者" size="large">
					<el-select @clear="consultId = ''" clearable v-model="consultId" placeholder="无" size="large"
						style="width: 240px">
						<el-option v-for="(item, index) in AllAuthor" :value="item.id" :label="item.consultName" />
					</el-select>
				</el-form-item>
				<el-form-item label="选择分类" size="large">
					<el-select @clear="classifyId = ''" clearable v-model="classifyId" placeholder="无" size="large"
						style="width: 240px">
						<el-option v-for="(item, index) in AllClassify" :value="item.id" :label="item.classifyName" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="query" size="large">搜索</el-button>
					<el-button type="primary" @click="createOrUpdate('')" size="large">新增</el-button>
					<el-button type="danger" size="large" @click="batchDelete">批量删除</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div>
			<el-table :data="tableData" style="width: 100%;margin-top: 10px;" border
				:header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="40" />
				<el-table-column fixed prop="id" label="id" width="50" />
				<el-table-column prop="articleName" label="文章名" width="110" show-overflow-tooltip />
				<el-table-column prop="articleIntroduction" label="文章简介" width="110" show-overflow-tooltip />
				<el-table-column prop="consultName" label="咨询师名" width="90" />
				<el-table-column label="缩略图" width="120">
					<template #default="scope">
						<el-avatar shape="square" size="large" :src="scope.row.url" />
					</template>
				</el-table-column>
				<el-table-column prop="count" label="阅读量" width="70" />
				<el-table-column prop="classifyName" label="所属分类" width="90" />
				<el-table-column prop="articleTime" label="创建时间" width="180" />
				<el-table-column label="审核状态" width="110">
					<template #default="scope">
						<el-tag type="warning" v-if="scope.row.status == 0">审核中</el-tag>
						<el-tag type="success" v-else-if="scope.row.status == 1">已审核</el-tag>
						<el-tag type="danger" v-else>审核未通过</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="状态" width="70">
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.del == 0">正常</el-tag>
						<el-tag type="danger" v-else>已删除</el-tag>
					</template>
				</el-table-column>
				<el-table-column fixed="right" label="操作" width="260">
					<template #default="scope">
						<el-button size="small" type="primary" @click="createOrUpdate(scope.row.id)">编辑</el-button>
						<el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
						<el-button size="small" type="primary"
							@click="searchArticleDetails(scope.row.id)">查看详情内容</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
			:size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
			@current-change="handleCurrentChange" />
		<el-dialog v-model="dialogFormVisible" :title="form.id ? '编辑' : '新增'" width="700" style="margin-bottom: 60px;"
			@close="handleClose">
			<el-form>
				<el-form-item label="文章标题" label-width="auto" label-position='top'>
					<el-input size="large" v-model="form.articleName" autocomplete="off" placeholder="请输入文章标题" />
				</el-form-item>
				<el-form-item label="文章简介" label-width="auto" label-position='top'>
					<el-input size="large" v-model="form.articleIntroduction" autocomplete="off"
						placeholder="请输入文章简介" />
				</el-form-item>
				<el-form-item label="咨询师作者" size="large" label-position='top'>
					<el-select v-model="form.consultId" placeholder="请选择咨询师" size="large">
						<el-option v-for="(item, index) in AllAuthor" :value="item.id" :label="item.consultName" />
					</el-select>
				</el-form-item>

				<el-form-item label="缩略图" label-position="top">
					<el-upload class="avatar-uploader" :action="baseURL+'upload'" :show-file-list="false"
						:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" name="file">
						<img v-if="imageUrl" :src="imageUrl" class="avatar" />
						<el-icon v-else class="avatar-uploader-icon">
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>


				<el-form-item label="文章内容详情" label-width="auto" label-position='top'>

					<QuillEditor v-model:content="form.content" contentType="html" :options="editorOptions" readonly
						:key="editorKey" style="min-height: 300px; border: 1px solid #ccc;width: 700px;" />

				</el-form-item>
				<el-form-item label="所属分类" size="large" label-position='top'>
					<el-select v-model="form.classifyId" placeholder="请选择分类" size="large">
						<el-option v-for="(item, index) in AllClassify" :value="item.id" :label="item.classifyName" />
					</el-select>
				</el-form-item>
				<el-form-item label="审核状态" size="large" label-position='top'>
					<el-select v-model="form.status" placeholder="请选择状态" size="large">
						<el-option :value="0" label="审核中" />
						<el-option :value="1" label="通过" />
						<el-option :value="2" label="不通过" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取消</el-button>
					<el-button type="primary" @click="dialogFormVisible = false; add()">确定</el-button>
				</div>
			</template>
		</el-dialog>
		<el-dialog v-model="dialogArticleDetails" title="内容详情" width="700" style="margin-bottom: 60px;"
			@close="handleClose">
			<el-form-item label="" label-width="auto" label-position='top'>
				<div>

					<QuillEditor v-model:content="form.content" contentType="html" :options="editorOptions" readonly
						:key="editorKey" style="min-height: 300px; border: 1px solid #ccc;width: 700px;" />

				</div>
			</el-form-item>
			<el-form-item label="" label-width="auto">
				<el-button size="large" type="primary" @click="() => { dialogArticleDetails = false; handleClose(); }"
					style="position:absolute;right: 0px;margin: 10px 0;">关闭</el-button>
			</el-form-item>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		getCurrentInstance,
		onMounted,
		reactive,
		ref
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	import BreadCrumb from "../../components/BreadCrumb.vue"
	import http from '@/util/http';
	
	const baseURL = http.defaults.baseURL
	const editorKey = ref(0)

	// 富文本内容同步
	const getMsg = (val) => {
		form.value.content = val
	}

	// 数据定义
	const AllAuthor = ref([])
	const AllClassify = ref([])
	const tableData = ref([])
	const consultId = ref('')
	const classifyId = ref('')
	const searchName = ref('')
	const currentPage = ref(1)
	const pageSize = ref(10)
	const size = 'default'
	const total = ref(0)
	const dialogFormVisible = ref(false)
	const dialogArticleDetails = ref(false)
	const imageUrl = ref('')
	const ids = ref('')
	import {
		QuillEditor
	} from '@vueup/vue-quill';
	import '@vueup/vue-quill/dist/vue-quill.snow.css';
	// 引入 Vue 3 适配器的样式
	const content = ref('');

	const show = () => {
		console.log(content.value)
	}

	const editorOptions = reactive({
		theme: 'snow', // 使用 snow 主题
		modules: {
			toolbar: [
				['bold', 'italic', 'underline', 'strike'], // 加粗、斜体、下划线、删
				['blockquote', 'code-block'], //引用，代码块
				[{
					'header': [1, 2, 3, 4, 5, 6, false]
				}], //几级标题
				[{
					'list': 'ordered'
				}, {
					'list': 'bullet'
				}], // 有序列表、无序列表
				[{
					'indent': '-1'
				}, {
					'indent': '+1'
				}], // 缩进
				[{
					'size': ['small', false, 'large', 'huge']
				}], // 字体大小
				[{
					'color': []
				}, {
					'background': []
				}], // 字体颜色，字体背景颜色
				[{
					'font': []
				}], //字体
				[{
					'align': []
				}], //对齐方式
				['link', 'image'] // 链接、图片
			]
		}
	})
	// 获取全局axios
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;

	// 表单数据
	const form = ref({
		id: "",
		articleName: "",
		articleIntroduction: "",
		consultId: null,
		url: "",
		content: "",
		count: 0,
		classifyId: null,
		articleTime: "",
		status: 0,
		del: 0,
		//consultName: "",
		//classifyName: ""
	})

	// 生命周期挂载
	onMounted(() => {
		query()
		getAllAuthor()
		getAllClassify()
	})

	// 数据请求方法
	const query = () => {
		axios.get( ///article/findArticlePage
			`article/findArticlePage?articleName=${searchName.value}&consultId=${consultId.value}&classifyId=${classifyId.value}&pageNum=${currentPage.value}&pageSize=${pageSize.value}`,
		).then(resp => {
			tableData.value = resp.data.list
			total.value = resp.data.total
			tableData.value.forEach(item => {
				//item.url = 'http://localhost:8080' + item.url
				item.url = item.url
			})
		})
	}

	const getAllAuthor = () => {
		axios.get(`/consult`).then(resp => {
			AllAuthor.value = resp.data
		})
	}

	const getAllClassify = () => {
		axios.get(`articleClassify/find`).then(resp => {
			AllClassify.value = resp.data
		})
	}

	// 分页事件
	const handleSizeChange = (val) => {
		pageSize.value = val;
		query();
	}

	const handleCurrentChange = (val) => {
		currentPage.value = val
		query();
	}

	// 选择事件
	const handleSelectionChange = (selection) => {
		ids.value = selection.map(item => item.id).join(',')
	}

	// 弹窗操作
	const createOrUpdate = (id) => {
		dialogFormVisible.value = true
		if (id === '') {
			handleClose()
		} else {
			axios.get(`/article/findById/${id}`).then(resp => {
				form.value = resp.data
				// resp.data.url为相对路径，展示时拼接完整路径
				//imageUrl.value = resp.data.url ? ('http://localhost:8080' + resp.data.url) : ''
				imageUrl.value = resp.data.url
			})
		}
	}

	const searchArticleDetails = (id) => {
		dialogArticleDetails.value = true
		axios.get(`/article/findById/${id}`).then(resp => {
			form.value = resp.data
			// resp.data.url为相对路径，展示时拼接完整路径
			//imageUrl.value = resp.data.url ? ('http://localhost:8080' + resp.data.url) : ''
			imageUrl.value = resp.data.url
		})
	}

	// 关闭弹窗重置
	const handleClose = () => {
		form.value = {

			articleName: "",
			articleIntroduction: "",
			consultId: null,
			url: "",
			content: "",
			count: 0,
			classifyId: null,
			articleTime: "",
			status: 0,
			id: "",
			//consultName: "",
			//classifyName: ""
		}
		imageUrl.value = ''
		editorKey.value++ // 🔄 关键：强制富文本重新渲染
	}

	// 上传图片处理
	const handleAvatarSuccess = (response) => {
		// 后端返回的是相对路径，比如 "/upload/20250717/xxxx.jpg"
		form.value.url = response.data; // 只存储相对路径
		//imageUrl.value = 'http://localhost:8080' + response.data; // 展示时拼接完整路径
		imageUrl.value = response.data;
	}
	const beforeAvatarUpload = (file) => {
		const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
		const isLt2M = file.size / 1024 / 1024 < 2;

		if (!isJPG) {
			this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
		}
		if (!isLt2M) {
			this.$message.error('上传头像图片大小不能超过 2MB!');
		}
		return isJPG && isLt2M;
	}

	// 新增/编辑提交
	const add = () => {
		if (!form.value.articleName) {
			return ElMessage.warning('请输入文章标题')
		}
		if (form.value.id === "") {
			axios.post('/article/add', form.value).then(resp => {
				if (resp.code === 200) {
					ElMessage.success('新增成功')
					dialogFormVisible.value = false // 新增成功后关闭弹窗
				} else {
					ElMessage.error('新增失败')
				}
			}).finally(() => {
				query()
			})
		} else {
			axios.put('/article/edit', form.value).then(resp => {
				if (resp.code === 200) {
					ElMessage.success('修改成功')
					dialogFormVisible.value = false // 编辑成功后关闭弹窗
				} else {
					ElMessage.error('修改失败')
				}
			}).finally(() => {
				query()
			})
		}
	}

	// 删除操作
	const remove = (id) => {
		ElMessageBox.confirm(
			'此操作将永久删除该文件, 是否继续?',
			'提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			axios.delete(`/article/remove/${id}`).then(resp => {
				if (resp.code === 200) {
					ElMessage.success('删除成功')
				} else {
					ElMessage.error('删除失败')
				}
			}).finally(() => {
				query()
			})
		}).catch(() => {
			ElMessage.info('取消删除')
		})
	}

	// 批量删除
	const batchDelete = () => {
		if (!ids.value) {
			return ElMessage.info('请选择要删除的数据')
		}
		ElMessageBox.confirm('此操作将永久删除选中数据, 是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			axios.delete(`/article/removeBatch`, {
				data: ids.value.split(',')
			}).then(res => {
				ElMessage.success('删除成功')
				query()
			})
		}).catch(() => {
			ElMessage.info('已取消删除')
		})
	}
</script>

<style scoped>
	.avatar-uploader {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 16px;
	}

	.avatar-uploader .avatar {
		width: 160px;
		height: 160px;
		border-radius: 16px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		object-fit: cover;
		border: 1px solid #eee;
		transition: box-shadow 0.3s;
	}

	.avatar-uploader .avatar:hover {
		box-shadow: 0 4px 24px rgba(0, 0, 0, 0.16);
	}

	.avatar-uploader .el-upload {
		border: 2px dashed #d9d9d9;
		border-radius: 16px;
		background: #fafbfc;
		width: 160px;
		height: 160px;
		display: flex;
		justify-content: center;
		align-items: center;
		transition: border-color 0.3s, background 0.3s;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
		background: #f0f9ff;
	}

	.el-icon.avatar-uploader-icon {
		font-size: 48px;
		color: #bfbfbf;
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>